package com.atguigu.cloud.gateway.filter;


import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Author: Worker Hu
 * @CreateTime: 2024-07-20  14:48
 */
//@Component
public class TokenGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                ServerHttpRequest request = exchange.getRequest();
                ServerHttpResponse response = exchange.getResponse();

                HttpHeaders headers = request.getHeaders();
                String name = config.getName();
                String value = config.getValue();
                System.out.println(value);
                List<String> list = headers.get(name);

                if(CollectionUtils.isEmpty(list)){
                    response.setStatusCode(HttpStatus.FORBIDDEN);// 设置响应码
                    return response.setComplete(); // 结束请求
                }
                System.out.println("走到这里第一步");
                if (!list.get(0).equals(value)) {
                    response.setStatusCode(HttpStatus.NOT_FOUND);
                    return response.setComplete();
                }
                System.out.println("走到这里第二步");
                return chain.filter(exchange);
            }
        };
    }
}


